package com.lv.suyiyong.hfr.ui

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.text.method.PasswordTransformationMethod
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.lv.common.base.BaseActivity
import com.lv.common.im.GenerateTestUserSig
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.network.model.DataResult
import com.lv.common.thirdparty.ShareUtils
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.DesUtil
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.common.widget.textview.SpanTextView.BaseSpanModel
import com.lv.common.widget.textview.SpanTextView.ClickSpanModel
import com.lv.common.widget.textview.SpanTextView.SpanClickListener
import com.lv.common.widget.textview.SpanTextView.TextSpanModel
import com.lv.service.bean.AroutBean
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.LoginByPassWordReqBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.utils.YgxAroutPageKt
import com.lv.service.webview.ConsealWebActivity
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.bean.TokenBean
import com.lv.suyiyong.hfr.databinding.ActivityLoginPasswordBinding
import com.tencent.qcloud.tuicore.TUILogin.login
import com.tencent.qcloud.tuicore.interfaces.TUICallback
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * 作者： ygx
 * 创建日期：2023/3/2 7:26 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：账号密码登录
 */
@Route(path = ARoutUtils.LoginByPassWordActivity)
class LoginByPassWordActivity : BaseActivity<ActivityLoginPasswordBinding>(), View.OnClickListener {
    @Autowired(name = ARoutUtils.AROUT_TAG)
    @JvmField
    var mTagARouter: AroutBean? = null
    private var isShowPassWord: Boolean = false
    private val serviceViewModel: ServiceViewModel by viewModel()
    private val mEditorViewModel by viewModels<EditorViewModel>()
    override fun getLayoutRes() = R.layout.activity_login_password
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())

    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            vm = mEditorViewModel
            StatusBarUtil.setHeightAndPadding(this@LoginByPassWordActivity, titleBar)
            mBinding.titleBar.onClickBackIcon { finish() }
            initSingleClickListener(ivEyes, tvRegisterLogin, tvForgotPwdLogin, btnLogin, tvAgree)
            ivEyes.setOnClickListener(this@LoginByPassWordActivity)

            mBinding.tvAgree.setText(
                createSpanTexts(),
                SpanClickListener { position ->
                    ConsealWebActivity.openUrl(this@LoginByPassWordActivity, "0")
                })

        }
    }


    override fun initConfig() {
        super.initConfig()

    }

    private fun login(res: UserInfo?) {
        res?.let {
            YgxUtilsKt.setAppToken(it.token, it.refreshtoken, it.id)

            // 在用户 UI 点击登录的时候调用
            login(
                this@LoginByPassWordActivity,
                GenerateTestUserSig.SDKAPPID,
                it.txaccid,
                it.txaccidpassword,
                object : TUICallback() {
                    override fun onError(code: Int, desc: String) {
                        LogUtils.e("onError")
                    }

                    override fun onSuccess() {
                        UserDbHelper.insertUserInfo(this@LoginByPassWordActivity, res)
                        LogUtils.e("onSuccess")
                        YgxUtilsKt.sendMessgeToSelf(it.txaccid, it.phone)
                        mTagARouter?.apply {
                            YgxAroutPageKt.LoginToTarget(mTagARouter, res)
                        }
//                        val comAndSpuList = res.comAndSpuList
//                        if (comAndSpuList.isNullOrEmpty()) {
//                            ARouter.getInstance().build(ARoutUtils.IndustrySelectedActivity)
//                                .withParcelable("userinfo", res)
//                                .navigation()
//                        }
                        finish()
                    }
                })
        }
    }

    override fun initData() {
        super.initData()
    }

    override fun initEvents() {
        super.initEvents()
        mBinding.etPhone.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence,
                start: Int,
                count: Int,
                after: Int
            ) {
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
//                    etPhone.paint.isFakeBoldText = !TextUtils.isEmpty(s)
                if (s.length == 11) {
                    mBinding.etCode.requestFocus()
                }

            }

            override fun afterTextChanged(s: Editable) {
            }
        })
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.iv_eyes -> {
                isShowPassWord = !isShowPassWord
                if (isShowPassWord) {
                    mBinding.ivEyes.LoadSrc(com.lv.common.R.drawable.icon_show_password)
                    mBinding.etCode.transformationMethod = null
                } else {
                    mBinding.ivEyes.LoadSrc(com.lv.common.R.drawable.icon_close_eyes)
                    mBinding.etCode.transformationMethod = PasswordTransformationMethod()
                }
            }

            R.id.tv_forgot_pwd_login -> {
                ARouter.getInstance().build(ARoutUtils.ForgetPasswordFristActivity).navigation()
            }

            R.id.tv_agree -> {
                mBinding.cbBox.isChecked = !mBinding.cbBox.isChecked
            }

            R.id.btn_login -> {
                repoLogin()
            }

            R.id.tv_register_login -> {
                ARouter.getInstance().build(ARoutUtils.LoginActivityURL).navigation()
                finish()
            }
        }
    }

    private fun repoLogin() {
        val account = mEditorViewModel.obMobile.get() ?: return showToast("手机号不能为空")
        val password = mEditorViewModel.obPassword.get() ?: return showToast("密码不能为空")

        val encode = DesUtil.encode(password)
        startLoading()
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.login(LoginByPassWordReqBody(account, encode)) }
                    .await()
            parseLoginResult(result)
        }

    }

    private fun parseLoginResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<UserInfo> { code, data, message, result ->
                login(data)
            }
            onBizError<TokenBean> { code, message, data ->

            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null) {
            //QQ回调
            ShareUtils.get().onQqActivityResult(requestCode, resultCode, data)
        }
    }

    private fun createSpanTexts(): List<BaseSpanModel>? {
        val spanModels: MutableList<BaseSpanModel> = ArrayList()
        val textSpanModel = TextSpanModel()
        textSpanModel.content = "我已经阅读并同意"
        spanModels.add(textSpanModel)
        val spanModel = ClickSpanModel()
        spanModel.content = "《速易甬隐私政策》"
        spanModels.add(spanModel)
//        textSpanModel = TextSpanModel()
//        textSpanModel.content = "，未注册的手机号将自动创建速易甬账号"
//        spanModels.add(textSpanModel)
//        spanModel = ClickSpanModel()
//        spanModel.content = "Lucy"
//        spanModels.add(spanModel)
        return spanModels
    }
}